const { v4: uuidv4 } = require('uuid');
const getTime = require('../utils/getTime'); 
const { executeQuery, executePagedQuery } = require('../utils/dataAccess');


exports.getRoleList = async (req, res, next) => {
    let sqlStatement = `SELECT 
        role_id as roleId,  
        role_name as roleName,  
        role_key as roleKey,  
        role_sort as roleSort,
        status as status,
        create_by as createBy,
        create_time as createTime,
        remark as remark
    FROM sys_role`;
    sqlStatement += ` ORDER BY role_sort`;

    try {
        const result = await executeQuery(sqlStatement);

        let sendData = result.rows;
        sendData.forEach((item)=>{
            item.admin = item.roleKey == 'admin' ? true : false;
        })
        res.json({
            code: 200,
            message: '查询成功',
            data: sendData
        });
    }
    catch (err) { next(err) }
}

exports.addRoles = async (req, res, next) => {

    try {
        if(!req.body.roleName || !req.body.roleKey || !req.body.roleSort || !req.body.status){
            throw new Error('参数错误');
        }
        
        let createBy = req.auth.user_name
    
        let sqlStatement = `INSERT INTO sys_role (role_name, role_key, role_sort, status, create_by, create_time, remark) VALUES ('${req.body.roleName}', '${req.body.roleKey}' , '${req.body.roleSort}', '${req.body.status}', '${createBy}', '${getTime()}', '${req.body.remark}')`;

        const result =  await executeQuery(sqlStatement);

        res.json({
            code: 200, 
            message: '添加成功',
            data: result.rows
        })
    }
    catch (err) { next(err) }
}

exports.roleMenuTreeselect = async (req, res, next) => {
    try {
        if(!req.body.roleId){
            throw new Error('参数错误');
        }
    
        let sqlStatement = `select * from sys_menu where 1=1`;
    
        let roleSql = `select 
            role_id as roleId,  
            role_name as roleName,  
            role_key as roleKey,  
            role_sort as roleSort,
            status as status,
            create_by as createBy,
            create_time as createTime,
            remark as remark
        from sys_role where role_id = ${req.body.roleId}`;
    
        let checkedKeysSql = `select menu_id from sys_role_menu where role_id = ${req.body.roleId}`;


        const result = await executeQuery(sqlStatement);
        const menuList = menuFilter(0,result.rows)
        const roleResult = await executeQuery(roleSql);
        const checkedKeysResult = await executeQuery(checkedKeysSql); // 获取选中的菜单id数组
        
        let sendData = {
            menus: convertTreeData(menuList),
            roleData: roleResult.rows[0],
            checkedKeys: checkedKeysResult.rows.map(item => item.menu_id)
        }
        res.json({
            code: 200,
            message: '查询成功',
            data: sendData
        })
    }
    catch (err) { next(err) }
}


exports.updateRole = async (req, res, next) => {
    try {
        if(!req.body.roleName || !req.body.roleKey || !req.body.roleSort || !req.body.status ){
            throw new Error('参数错误');
        }
    
        let updateBy = req.auth.user_name;
        let updateTime = getTime();
    
        let sqlStatement = `update sys_role set role_name = '${req.body.roleName}', role_key = '${req.body.roleKey}', role_sort = ${req.body.roleSort}, status = '${req.body.status}',remark = '${req.body.remark}', update_by = '${updateBy}', update_time = '${updateTime}' where role_id = ${req.body.roleId}`; 
    
        // 清除sys_role_menu中原有数据
        let deleteSql = `delete from sys_role_menu where role_id = ${req.body.roleId}`; 
    
        let menuIds = req.body.menuIds;
        
        let deleteResult = null
        let insertResult = null
    
        // 插入sys_role_menu数据
        let insertSql = `insert into sys_role_menu (role_id, menu_id) values ${menuIds.map(item => `(${req.body.roleId}, ${item})`).join(',')}`;

        let result = await executeQuery(sqlStatement); // 执行更新操作

        if(menuIds.length > 0){
            deleteResult = await executeQuery(deleteSql); // 清除sys_role_menu中原有数据
            insertResult = await executeQuery(insertSql); // 插入sys_role_menu数据
        }

        res.json({
            code: 200, 
            message: '更新成功',
            data: {result, deleteResult, insertResult} // 返回更新结果、清除结果和插入结果的组合对象，方便前端处理
        });
    } 
    catch (err) { next(err) }

}

// 删除角色
exports.deleteRole = async (req, res, next) => {
    try {
        if(!req.body.roleId){
            throw new Error('参数错误');
        }
    
        let sqlStatement = `delete from sys_role where role_id = ${req.body.roleId}`; // 删除角色数据
        let deleteSql = `delete from sys_role_menu where role_id = ${req.body.roleId}`; // 清除sys_role_menu中原有数据
        let deleteDept = `delete from sys_role_dept where role_id = ${req.body.roleId}`; // 清除sys_dept_role中原有数据
        let deleteUser = `delete from sys_user_role where role_id = ${req.body.roleId}`; // 清除sys_user_role中原有数据

        let result = await executeQuery(sqlStatement); // 执行删除操作
        let deleteResult = await executeQuery(deleteSql); // 清除sys_role_menu数据
        let deleteDeptResult = await executeQuery(deleteDept); // 清除sys_dept_role数据
        let deleteUserResult = await executeQuery(deleteUser); // 清除sys_user_role数据
        res.json({
            code: 200, 
            message: '删除成功', 
            data: {result, deleteResult, deleteDeptResult, deleteUserResult}
        }); 
    }
    catch (err) { next(err) }
}

// 查询角色关联用户
exports.getRoleUser = async (req, res, next) => {

    try {
        if(!req.body.roleId){
            throw new Error('参数错误');
        }
    
        let sqlStatement = `SELECT 
            u.user_id AS userId,
            u.create_time AS createTime,
            u.dept_id AS deptId,
            u.user_name AS userName,
            u.nick_name AS nickName,
            d.dept_name AS deptName,
            r.role_name AS roleName
        FROM 
            sys_user u
        JOIN 
            sys_dept d ON u.dept_id = d.dept_id
        JOIN 
            sys_user_role ur ON u.user_id = ur.user_id
        JOIN 
            sys_role r ON ur.role_id = r.role_id
        WHERE 
            ur.role_id = ${req.body.roleId}`;


        let result = await executePagedQuery(sqlStatement, req.body.pageSize, req.body.pageNo, 'createTime'); // 执行查询操作
        res.json({
            code: 200, 
            message: '查询成功',
            data: result,
        });
    }
    catch (err) { next(err) }
}


// 关联用户到角色
exports.addRoleUser = async (req, res, next) => {
    try {
        if(!req.body.userId || !req.body.roleId){
            res.json({code: 400, message: '参数错误'});
            return;
        }
    
        let sqlStatement = `insert into sys_user_role (user_id, role_id) values (${req.body.userId}, ${req.body.roleId})`; // 插入sys_user_role数据

        let result = await executeQuery(sqlStatement); // 执行插入操作
        res.json({
            code: 200, 
            message: '关联成功', 
            data: result.rows // 返回受影响的行数，方便前端处理
        });
    }
    catch (err) { next(err) }
}

// 取消用户关联角色
exports.deleteRoleUser = async (req, res, next) => {
    try {
        if(!req.body.userId || !req.body.roleId){
            throw new Error('参数错误');
        }
        let sqlStatement = `delete from sys_user_role where user_id = ${req.body.userId} and role_id = ${req.body.roleId}`; // 删除sys_user_role数据

        let result = await executeQuery(sqlStatement); // 执行删除操作
        res.json({
            code: 200, 
            message: '取消关联成功', 
            data: result.rows // 返回受影响的行数，方便前端处理
        });
    }
    catch (err) { next(err) }
}





function menuFilter(id, data){
    let result = [];
    for(let i = 0; i < data.length; i++){
        if(data[i].parent_id == id){
            result.push(data[i]);
            data[i].children = menuFilter(data[i].menu_id, data);
        }
    }
    return result;
}

// 转换树形结构的值
function convertTreeData(data) {
    return data.map(item => ({ 
        id: item.menu_id,
        label: item.menu_name,
        type: item.menu_type,
        children: item.children ? convertTreeData(item.children) : [] 
    }));
}